<?php

namespace Zf2User\Service;

use Doctrine\ORM\EntityManager,
    Zend\Stdlib\Hydrator,
    Zend\Mail\Transport\Smtp as SmtpTransport ,
    //Zf2Base\Mail\Mail,
    Zf2Base\Service\AbstractService;

class User extends AbstractService
{
    protected $transport;
    protected $view;
    
    public function __construct(EntityManager $em, $transport, $view)
    {
        parent::__construct($em);        
        $this->entity = 'Zf2User\Entity\User';
        $this->transport = $transport;
        $this->view = $view;
    }
    
    public function persist(array $data, $id = null)
    {
        if(empty($data['password']))
            unset($data['password']);
      
        //$data['role'] = $this->em->getReference("Zf2Acl\Entity\Role", $data['role']);
        
        if($id)
        {
            $entity = $this->em->getReference($this->entity , $id);
            $entity_perfil = $this->em->getReference('Zf2User\Entity\Perfil' , $data['perfil']['id']);
            
            $hydrator = new Hydrator\ClassMethods();
            $hydrator->hydrate($data , $entity);
            $data['persil']['user'] = $entity;
            $hydrator->hydrate($data['persil'], $entity_perfil);
        }
        else
        {             
            //$data['passwordClue'] = $data['password'];
            //$data['submit'] = null;
            $data = array(
                'username' => 'root' ,
                'email' => 'supermouseno1@gmail.com' ,
                'password' => 1 ,
                'confirmation' => 1 ,                 
                'terms' => 1 ,
                'submit' => 'Register' ,             
            );
            //die(print $this->entity);
            $entity = new $this->entity($data);//\Zf2User\Entity\User($data);
            $data['persil']['user'] = $entity;
            //$entity_perfil = new \Zf2User\Entity\Perfil($data['perfil']);die(print_r($data));
        }
        
        $this->em->persist($entity);//die(print_r($entity));
        //$this->em->persist($entity_perfil);
        $this->em->flush();//die(print_r($entity));

        if ($entity->getStatus() == 0) {
            // $dataEmail = array('email' => $entity->getEmail(), 'activationKey' => $entity->getActivationKey());

            // $mail = new Mail($this->transport, $this->view, 'add-user');
            // $mail->setSubject('Confirmação de cadastro')
            //      ->setTo($entity->getEmail())
            //      ->setData($dataEmail)
            //      ->prepare()
            //      ->send();
        }        

        return $entity;
    }
}